package com.ruoyi.nlp.utils;


import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 按照值排序map
 * @author yjh
 */
public class MapOrderByValUtil {

	/**
	 * 
	 * @param map
	 * @param top 取前多少条
	 * @param isDesc 是否降序
	 * @return
	 */
	public static List<String> getTopKey(Map<String,Integer> map,int top,boolean isDesc){
		
		List<String> result = new LinkedList<String>();
		
		Integer[] values = map.values().toArray(new Integer[]{});
		String[] keys = map.keySet().toArray(new String[]{});
		for(int i=0;i<values.length;i++){
			for(int j=i+1;j<values.length;j++){
				if(isDesc){
					if(values[i] < values[j]){
						jiaoHuan(values,i,j);
						jiaoHuan(keys,i,j);
					}
				}else{
					if(values[i] > values[j]){
						jiaoHuan(values,i,j);
						jiaoHuan(keys,i,j);
					}
				}
			}
		}
		if(top > 0){
			for(int i = 0;i < top;i++){
				if(i <= keys.length - 1){
					result.add(keys[i]);
				}else{
					break;
				}
			}
		}else{
			for(int i = 0;i < keys.length;i++){
				result.add(keys[i]);
			}
		}
		
		return result;
	}
	
	private static void jiaoHuan(Object[] obj,int before,int after){
		
		Object o = null;
		o = obj[after];
		obj[after] = obj[before];
		obj[before] = o;
	}
	
}
